# coding=utf-8
"""
从mongo的表中同步数据到redis中
1. mongo:  [gps.curgps ]
    to
    redis: [RescueVeh:CurGps:xxx]

"""
import redis
import logging
from pymongo import *
from logmod import LogMgr

""" mongo configure """
#mongoUrl = 'mongodb://gps:gps@192.168.1.62/?authSource=gps'
mongoUrl = 'mongodb://gps:gps@localhost:37017/?authSource=gps'
dbName = 'gps'

""" redis configure """
redisClient =  redis.StrictRedis(host='192.168.1.36', port=6379, db=1)

""" logging configure """
logger = LogMgr.getLogger('mongo')
logger.setLevel(logging.DEBUG)

def getVehKey(hostid):
    return 'RescueVeh:CurGps:{}'.format(hostid)

def query_all():
    """
    查询mongo中当前表的gps数据
    :return: return list like this
    {u'hostid': 73L, u'devid': u'3870010023',
    u'lon': 118.818504, u'time': datetime.datetime(2016, 6, 24, 2, 1), u'lat': 31.972742, u'alt': 20L, u'speed': 0.0}
    """
    client = MongoClient(mongoUrl)
    db = client[dbName]
    #print repr(db)
    collection = db['curgps']
    cursor = collection.find(filter={'hostid':{'$ne':0}},
                             projection={'_id': False, 'devid': True, 'hostid':True, 'time':True,
                                         'lat':True, 'lon':True, 'alt':True, 'speed':True,
                                         'ang':True, 'acc':True, 'rectm':True, 'gwid':True, 'type':True})

    result = []

    for obj in cursor:
        result.append(obj)
        # print  type(obj)
        logger.debug(obj)
    cursor.close()
    client.close()
    return result

def save_to_redis(valList) :
    for item in valList:
        hostid = item['hostid']
        logger.info("save %s to redis: %s", hostid, item)
        redisClient.hmset(getVehKey(hostid), item)


if __name__ == "__main__":
    #query_all()
    #print getVehKey(123)
    save_to_redis(query_all())